package com.gitee.chessboard.jdbc.parser;

import com.gitee.chessboard.jdbc.JdbcManager;

import java.util.stream.Collectors;

/**
 * 将对象转换成创建表的sql
 *
 * @author 敲代码的旺财
 * @date 2021/11/18 14:53
 */
public class CreateTableParser implements Parser {
    /**
     * jdbc的管理器
     */
    private JdbcManager jdbcManager;

    public CreateTableParser(JdbcManager jdbcManager) {
        this.jdbcManager = jdbcManager;
    }

    /**
     * 将对象转成创建表的sql
     *
     * @param obj 需要解析的对象
     * @return 建表sql语句
     */
    @Override
    public String convert(Object obj) {
        ParserHandler parserHandler = jdbcManager.getParserHandler(obj);
        StringBuilder sb = new StringBuilder("CREATE TABLE If Not Exists " + parserHandler.getTableName());
        sb.append("(");
        String column = parserHandler.getTableFieldNameAndTableFieldType().entrySet()
                .stream()
                .map(m -> m.getKey() + " " + m.getValue())
                .collect(Collectors.joining(","));
        sb.append(column);
        sb.append(", PRIMARY KEY("+parserHandler.getTableId()+")");
        sb.append(")");
        return sb.toString();
    }
}
